package com.lz.library.adapter

import android.util.SparseIntArray
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding

/**
 *  author: you : 2020/4/25  initialCapacity
 */
abstract class BindingMultiAdapter<T : Multiple>(initData: List<T>? = null, multipleCapacity: Int = 4)
    : com.lz.library.adapter.BaseAdapter<T, BindingViewHolder>(initData) {
    /**
     * 不同itemViewType对应的布局id
     */
    private val layoutResIds = SparseIntArray(multipleCapacity)

    /**
     * 不同itemViewType对应的variableId
     */
    private val variableIds = SparseIntArray(multipleCapacity)

    /**
     * 添加type对应的布局,设置适配器前调用,可以在子类实现构造方法中先添加好
     * @param itemViewType
     * @param layoutResId
     */
    protected fun addItemLayoutType(itemViewType: Int, @LayoutRes layoutResId: Int) =
        layoutResIds.put(itemViewType, layoutResId)

    /**
     * 添加type对应的ViewBinding设置的属性
     * @param itemViewType
     * @param variableId  as  BR. ...
     */
    protected fun addItemVariableType(itemViewType: Int, variableId: Int) =
        variableIds.put(itemViewType, variableId)

    override fun getItemViewType(position: Int): Int = data[position].viewType

    override fun onCreateItem(parent: ViewGroup, viewType: Int): BindingViewHolder {
        val layoutResId = layoutResIds[viewType]
        check(layoutResId == 0) { "You must addItemType formats viewType = $viewType" }
        return BindingViewHolder(DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, layoutResId, parent, false).root)
    }

    override fun onBindViewHolder(vh: BindingViewHolder, position: Int) {
        val variableId = variableIds.get(vh.itemViewType, -1)
        if (variableId > 0) {
            vh.getBinding<ViewDataBinding>().setVariable(variableId, getItem(position).viewType)
        }
    }

    override fun onViewRecycled(vh: BindingViewHolder) = vh.getBinding<ViewDataBinding>().unbind()
}